# encoding:utf-8
import os
import json
from ad_string import ad_str_fullscreen, ad_str_small


class apk_utg(object):
    def __init__(self, path):
        info = eval(open(path + '\\' + 'utg.js').read()[11:])
        self.app_main_activity = info['app_main_activity']
        self.app_num_total_activities = info['app_num_total_activities']
        self.num_effective_events = info['num_effective_events']
        self.num_reached_activities = info['num_reached_activities']
        self.num_edges = info['num_edges']
        self.num_nodes = info['num_nodes']
        self.app_package = info['app_package']
        self.nodes = info['nodes']  # js file content
        self.edges = info['edges']  # js file content
        self.fnode_date_str = {}  # state two name mapping
        self.fnode_str_date = {}  # state two name mapping
        self.fnode_node_act = {}  # state node act mapping
        self.fnode_str_structure = {}  # state_str structure_str mapping
        self.fnode_str_info = {}  # str all_info mapping
        self.bulid_fnode()  # state two name mapping
        self.node_state = {}  # state detail info
        for file in os.listdir(path + '\\states'):
            if file.endswith('json'):
                try:
                    self.node_state[self.fnode_date_str[file[:-5].replace('state', 'screen')]] = json.loads(
                        open(path + '\\states\\' + file).read())
                except:
                    continue
        self.ad_view_full = {}  # full ad view indicator {state_str:-1}
        self.ad_view_small = {}  # small ad view indicator {state_str:info}
        self.ad_view_banner = {}  # small ad view indicator {state_str:info}
        self.detect_admob()
        self.dialog = []
        self.detect_dialog()
        # print(self.dialog)
        self.first_node = -1
        self.seek_first_node()
        self.from_BACK_to = {}
        self.from_AMST_to = {}
        self.analyse_back()
        pass

    def seek_first_node(self):
        for no in self.nodes:
            if 'FIRST' in no['label']:
                self.first_node = no['state_str']
                break

    def bulid_fnode(self):
        for no in self.nodes:
            self.fnode_date_str[no['image'][no['image'].find('/') + 1:-4]] = no['state_str']
            self.fnode_str_date[no['state_str']] = no['image'][no['image'].find('/') + 1:-4]
            self.fnode_node_act[no['state_str']] = no['activity']
            self.fnode_str_structure[no['state_str']] = no['structure_str']
            self.fnode_str_info[no['state_str']] = no

    def analyse_back(self):
        for eg in self.edges:
            for ev in eg['events']:
                # self.from_AMST_to[eg['from']]=[]
                if 'BACK' in ev['event_str']:
                    try:
                        self.from_BACK_to[eg['from']].append(eg['to'])
                        break
                    except:
                        self.from_BACK_to[eg['from']] = []
                        self.from_BACK_to[eg['from']].append(eg['to'])
                        break
                if 'am start' in ev['event_str'] and self.fnode_str_info[eg['from']]['package'] != self.app_package:
                    self.from_AMST_to[eg['from']] = eg['to']

    def detect_dialog(self):
        for node, state in self.node_state.items():
            view_class = [view['class'] for view in state['views']]
            # print(node, view_class)
            # print(view_class.count('android.widget.TextView'),view_class.count('android.widget.Button'))
            if view_class.count('android.widget.TextView') >= 1 and view_class.count('android.widget.Button') == 2:
                self.dialog.append(node)

    def detect_admob(self):
        for node, state in self.node_state.items():
            # full screen ad
            ad_exist_full = 0
            for ad_s in ad_str_fullscreen:
                # print(ad_s.lower(),state['foreground_activity'])
                if ad_s.lower() in state['foreground_activity'].lower():
                    ad_exist_full = 1
                    break
            if ad_exist_full == 1:
                self.ad_view_full[node] = -1  # 'full_screen_ad'
                continue
            else:  # small ad
                if 'com.android.browser' in state['foreground_activity'].lower():
                    continue
                for view in state['views']:
                    if view['class'] == 'android.webkit.WebView' or view['class'] == 'android.widget.ViewFlipper':
                        web_size = view['size']
                        wtemp_size = web_size.split('*')
                        aw = int(wtemp_size[0])
                        bw = int(wtemp_size[1])
                        web_size = aw * bw
                        if web_size == 0:
                            continue
                        if web_size * 1.5 <= 1920 * 1080:
                            if aw > bw:
                                proportion = aw * 1.0 / bw
                            else:
                                proportion = bw * 1.0 / aw
                            if proportion > 3:
                                self.ad_view_banner[node] = view['bounds']
                            else:
                                self.ad_view_small[node] = view['bounds']
                            break
